import { HttpStatus, Injectable } from '@nestjs/common';
import { AxiosResponse } from 'axios';
import { FastifyReply, FastifyRequest } from 'fastify';
import { Http } from '../../util';

@Injectable()
export class ApiService {

    /**
     * @description 数据请求工具实例对象
     * @type {Http}
     * @memberof ApiService
     */
    http: Http = Http.getInstance();

    /**
     * 执行Get行为
     *
     * @param {FastifyRequest} request
     * @param {FastifyReply} response
     * @memberof ApiService
     */
    public async executeGetAction(request: FastifyRequest, response: FastifyReply) {
        // 截取/api
        let url = request.url.slice(4);
        if (Object.is(url, '/app/environment')) {
            response.code(HttpStatus.OK).send({ RunMode: 'PLAYER' });
        } else {
            const getResult = await this.http.get(request, response, url);
            this.parseResponse(request, response, getResult);
        }
    }

    /**
     * 执行Post行为
     *
     * @param {FastifyRequest} request
     * @param {FastifyReply} response
     * @memberof ApiService
     */
    public async executePostAction(request: FastifyRequest, response: FastifyReply, body: any) {
        // 截取/api
        let url = request.url.slice(4);
        const result = await this.http.post(request, response, url, body);
        this.parseResponse(request, response, result);
    }

    /**
     * 解析响应
     *
     * @public
     * @param {FastifyRequest} _req
     * @param {FastifyReply} res
     * @param {AxiosResponse<any>} aRes
     * @return {*}  {Promise<any>}
     * @memberof ApiService
     */
    public async parseResponse(_req: FastifyRequest, res: FastifyReply, aRes: AxiosResponse<any>): Promise<any> {
        if (aRes) {
            try {
                const headers: Record<string, any> = aRes.headers;
                for (const key in headers) {
                    if (Object.prototype.hasOwnProperty.call(headers, key)) {
                        const val = headers[key];
                        res.header(key, val);
                    }
                }
                res.header('connection', 'keep-alive');
                res.status(HttpStatus.OK).send(aRes.data);
            } catch (err) {
                res.status(HttpStatus.INTERNAL_SERVER_ERROR).send(err.message);
            }
        }
    }
}
